package jpm.numbertriangle;

import static jpm.common.AssertUtils.ensureNotNull;

import java.util.List;

import jpm.common.JPMException;
import jpm.common.JPMException.ErrorCode;

public class NumberTriangle {
	
	public static int getMaxSum(List<List<Integer>> listOfList) {
		ensureValid(listOfList);
		
		int size = listOfList.size();
		if (size == 1)
			return listOfList.get(0).get(0);
				
		List<Integer> lastButOne = listOfList.get(size - 2);
		List<Integer> last = listOfList.get(size - 1);
		for (int i = 0; i < last.size() - 1; i++) {
			int max = Math.max(last.get(i), last.get(i + 1));
			lastButOne.set(i, lastButOne.get(i) + max);
		}
		
//		for (int i = 0; i < lastButOne.size(); i++) {
//			System.out.print(lastButOne.get(i) + " ");
//		}
//		System.out.println();
		
		listOfList.remove(size - 1);
		
		return getMaxSum(listOfList);
	}
	
	static void ensureValid(List<List<Integer>> listOfList) {
		ensureNotNull(listOfList, "listOfList is null");

		for (int i = 0; i < listOfList.size(); i++) {
			List<Integer> list = listOfList.get(i);

			if (list.size() != i + 1)
				throw new JPMException().errorType(
						ErrorCode.ERROR_INVALID_INPUT).message(
						"Error in line [" + (i + 1) + "] - Invalid no of elements. Expected [" 
						+ (i + 1) + "], Actual ["
								+ list.size() + "]");
		}
	}
}
